from django.template import RequestContext
from django.db import IntegrityError
from django.shortcuts import render_to_response, redirect
from models import RSMGroup
from RSM.util import verifySessionValidity, getRSMGroup, getUserNames, getRSMUser, isSafeName, getExtend
import hashlib

def allGroups(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag

    currentUser = getRSMUser(request.user.username)
    groupsNames = [(u.groupName, hashlib.md5(u.groupName).hexdigest()) for u in currentUser.groups.all()]
    
    return render_to_response("my_groups/viewgroups.html", {"groups": groupsNames, "username": request.user.username}, context_instance=RequestContext(request))
    
def createGroup(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag
    
    return render_to_response("my_groups/addgroup.html", {"username": request.user.username}, context_instance=RequestContext(request))

def actualAdd(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag
    
    currentUser = getRSMUser(request.user.username)
    groupName = request.POST.get(u'groupname')
    if not groupName or not isSafeName(groupName):
        return render_to_response("basic/errorPage.html", {'extend': getExtend(request), 'message': "Illegal group name."}, context_instance=RequestContext(request))
    try:
        newGroup = RSMGroup(owner = request.user.username, groupName = groupName)
        newGroup.save()
    except IntegrityError:
        return render_to_response("basic/errorPage.html", {'extend': getExtend(request), 'message': "Group with this name already exists."}, context_instance=RequestContext(request))
    currentUser.groups.add(newGroup)

    return redirect('/groups/allGroups/')

def removeGroup(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag
    
    current_user = getRSMUser(request.user.username)
    groupName = request.POST.get(u'groupname')
    group = getRSMGroup(request.user.username,groupName)
    current_user.groups.remove(group)
    group.delete()
    
    return redirect('/groups/allGroups/')

def editGroup(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag
    
    groupName =  request.POST.get(u'group')
    group = getRSMGroup(request.user.username,groupName)
    currentUser = getRSMUser(request.user.username)
    friends_not_in_group = getUserNames(currentUser.friends.all())
    for u in getUserNames(group.members.all()):
        friends_not_in_group.remove(u)
    hasToAdd = bool(len(friends_not_in_group)) 
    friends_in_group = getUserNames(currentUser.friends.all())
    for u in friends_not_in_group:
        friends_in_group.remove(u)
    hasToRemove = bool(len(friends_in_group)) 
    variables = {"fgroups":friends_in_group, "fngroups":friends_not_in_group,"hasToRemove":hasToRemove, "hasToAdd":hasToAdd, "username":request.user.username, "group": groupName}
    return render_to_response("my_groups/edit_group.html", variables, context_instance=RequestContext(request))       

def editFrendsInGroup(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag
    
    groupName = request.POST.get(u'groupname')
    group = getRSMGroup(request.user.username,groupName)
    shouldAdd = request.POST.get(u'action') == "addFriend"
    for o in request.POST.getlist(u'friends'):
        friend = getRSMUser(o)
        if (shouldAdd):
            group.members.add(friend)
        else:
            group.members.remove(friend)
    
    currentUser = getRSMUser(request.user.username)   
    friends_not_in_group = getUserNames(currentUser.friends.all())
    for u in getUserNames(group.members.all()):
        friends_not_in_group.remove(u)
    hasToAdd = bool(len(friends_not_in_group)) 
    friends_in_group = getUserNames(currentUser.friends.all())
    for u in friends_not_in_group:
        friends_in_group.remove(u)
    hasToRemove = bool(len(friends_in_group)) 
    variables = {"fgroups":friends_in_group, "fngroups":friends_not_in_group,"hasToRemove":hasToRemove, "hasToAdd":hasToAdd, "username":request.user.username, "group": groupName}
    return render_to_response("my_groups/edit_group.html", variables, context_instance=RequestContext(request))       
